I solved ‘main redeclared in this block’ Error
Hi, this is Charu from Classmethod. In this very short blog, we will find out how to solve 'main redeclared in this block' error in GoLang. This error is mainly related to your go main files and package. Let's dig deeper into this.
What I wanted to achieve?
Since I am new to Go, I was practicing Go by trying different small problems. I wanted to keep all the small problems under one folder or package. But then, as soon as I added my second GoLang file, it gave me an error saying 'main redeclared in this block'.
What I did?
In Go, each package can have only one main function, which is the entry point of the program. When you create multiple files in the same folder and declare a func main()
in each, the Go compiler sees multiple entry points in the same package, leading to the "main redeclared in this block" error.
This was my files structure:
/go_exercises
/problem1_main.go // problem 1, func main()
/problem2_main.go // problem 2, func main()
How to solve the error?
There are 2 ways to solve this error. I followed the first option, but I will explain all the two options.
Option 1:
You can organize each problem in its own subfolder, with each subfolder containing its own main function in its package. Here’s how you can structure it:
/go_exercises
/problem1
main.go // package main, func main()
/problem2
main.go // package main, func main()
This way, you can run each problem separately by navigating into its directory and running go run main.go
Option 2:
If you want to keep all your problems in one package, you can create a single main.go file with the main function, and then separate files for each problem's logic encapsulated in uniquely named functions.
For example:
// main.go package main import "fmt" func main() { fmt.Println("Select a problem to run:") fmt.Println("1: Problem 1") fmt.Println("2: Problem 2") // Add more problems as needed var choice int fmt.Scanln(&choice) switch choice { case 1: problem1() case 2: problem2() // Add more cases as needed default: fmt.Println("Invalid choice") } } // problem1.go func problem1() { // Problem 1 logic here } // problem2.go func problem2() { // Problem 2 logic here }
This way, you can keep all your problems in one folder without multiple main functions, and you can easily run the specific problem's logic you want to test by selecting it when you run main.go.
Conclusion:
In this blog, we learned how include multiple GoLang main files under one folder. Try practicing Go without the load of managing multiple folders.
Thank you for reading!
Happy Learning:)